package com.ionehe.group.common.uaa.ex.application.rest;

import cn.hutool.http.HttpStatus;
import com.ionehe.group.common.io.Response;
import com.ionehe.group.common.uaa.ex.application.converter.ManageInfoVOConvert;
import com.ionehe.group.common.uaa.ex.application.model.AdminLoginVo;
import com.ionehe.group.common.uaa.ex.application.model.ManageInfoVO;
import com.ionehe.group.common.uaa.ex.domain.service.AdminReadService;
import com.ionehe.group.common.uaa.ex.domain.service.AdminWriteService;
import com.ionehe.group.common.uaa.ex.dto.ManageInfoDTO;
import com.ionehe.group.common.uaa.ex.utils.LoginUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Copyright (c) 2020 ionehe.com
 * Date: 2020/9/15
 * Time: 下午10:58
 *
 * @author 2020年 <a href="mailto:a@ionehe.com">秀</a>
 * 后台用户管理Controller
 */
@RestController
@Api(hidden = true, value = "uaa-后台管理员(平台管理员、开发者)登陆相关服务", tags = "uaa-管理员(平台管理员、开发者)登陆相关服务")
@ApiIgnore
@RequestMapping("/api/uaa/login")
public class UaaAdminLoginController {
    @Autowired
    private AdminWriteService adminWriteService;
    @Autowired
    private AdminReadService adminReadService;
    @Autowired
    private LoginUtils loginUtil;
    @Value("${jwt.tokenHeader:Authorization}")
    private String tokenHeader;
    @Value("${jwt.tokenHead:Bearer }")
    private String tokenHead;

    @ApiOperation(value = "用户注册")
    @PostMapping(value = "/register")
    public Response<ManageInfoVO> register(@Validated @RequestBody ManageInfoVO adminInfo) {
        Response<ManageInfoDTO> res = adminWriteService.register(ManageInfoVOConvert.INSTANCE.vo2dto(adminInfo));
        if (!res.success() || Objects.isNull(res.getData())) {
            return Response.no(res.getMessage());
        }
        return Response.yes(ManageInfoVOConvert.INSTANCE.dto2vo(res.getData()));
    }

    @ApiOperation(value = "登录以后返回token")
    @PostMapping
    public Response<Map<String, String>> login(@Validated @RequestBody AdminLoginVo adminLoginParam, HttpServletRequest request) {
        adminLoginParam.setKey(getRequestIp(request) + ":" + adminLoginParam.getKey());
        Response<String> res = adminWriteService.login(ManageInfoVOConvert.INSTANCE.vo2dto(adminLoginParam));
        if (!res.success() || Objects.isNull(res.getData())) {
            return Response.no(res.getError(), res.getMessage());
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", res.getData());
        tokenMap.put("tokenHead", tokenHead);
        return Response.yes(tokenMap);
    }

    @ApiOperation("获取当前登陆用户信息")
    @GetMapping("/getUserByToken")
    public Response<ManageInfoVO> getUserByToken(HttpServletRequest request) {
        String authHeader = request.getHeader(tokenHeader);
        String authToken = authHeader.substring(this.tokenHead.length());
        Response<ManageInfoDTO> res = adminReadService.getAdminByToken(authToken);
        if (!res.success()) {
            return Response.no(res.getMessage());
        }

        return Response.yes(ManageInfoVOConvert.INSTANCE.dto2vo(res.getData()), HttpStatus.HTTP_OK, "Access.success.general", null);
    }

    @ApiOperation(value = "刷新token")
    @GetMapping(value = "/refreshToken")
    public Response<Map<String, String>> refreshToken(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        Response<String> res = adminWriteService.refreshToken(token);
        if (!res.success() || Objects.isNull(res.getData())) {
            return Response.no(res.getMessage());
        }
        String refreshToken = res.getData();
        if (refreshToken == null) {
            return Response.no("token已经过期！");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", refreshToken);
        tokenMap.put("tokenHead", tokenHead);
        return Response.yes(tokenMap);
    }

    @ApiOperation(value = "登出功能")
    @PostMapping(value = "/logout")
    public Response<Boolean> logout(HttpServletRequest request) {
        String authHeader = request.getHeader(this.tokenHeader);
        if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
            String token = authHeader.substring(this.tokenHead.length());
            return loginUtil.logout(token);
        }
        return Response.yes(true);
    }


    private String getRequestIp(HttpServletRequest request) {
        if (request.getHeader("x-forwarded-for") == null) {
            return request.getRemoteAddr();
        }
        return request.getHeader("x-forwarded-for");
    }
}
